//
//  RCLoginView.m
//  RocketProject
//
//  Created by chen jiedan on 13-7-1.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCLoginView.h"
#import "IManager+LoginRequest.h"
#import "RCLoginDataModel.h"
#import "UIColor-Expanded.h"
#import "CommonDefines.h"
#import "GloableEngineService.h"
#import "AppDelegate.h"
#import "GloableEngineService.h"
#import "NSString+NSString_Ex_.h"
#import "FrameworkRelativeDefines.h"


#define kTagUserName            101
#define kTagPassWord            102

@implementation RCLoginView{
    UITextField *_userNameLabel;
    UITextField *_userPassword;
    UIActivityIndicatorView *_indicatorView;
    UILabel *_userNameWrongLabel;
    UIButton *_loginBtn;
    UIButton *_regBtn;
}

@synthesize delegate = _delegate;
@synthesize userNameLabel = _userNameLabel;
@synthesize userPassword = _userPassword;


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        UIButton *bgBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
        [self addSubview:bgBtn];
        [bgBtn addTarget:self action:@selector(bgClick) forControlEvents:UIControlEventTouchUpInside];
        [bgBtn release];
        
        UIImageView *bg1 = [[[UIImageView alloc] initWithFrame:CGRectMake(14, 17, 320-14*2, 47)] autorelease];
        UIImage *img1 = [UIImage imageNamed:@"form_bg1"];
        bg1.image = img1;
        [self addSubview:bg1];
        
        UIImage *emailImg = [UIImage imageNamed:@"icon_email"];
        UIImageView *email = [[UIImageView alloc] initWithFrame:CGRectMake(15, 20, emailImg.size.width, emailImg.size.height)];
        email.image = emailImg;
        [bg1 addSubview:email];
        [email release];
        
        UILabel *emailNote = [[UILabel alloc] initWithFrame:CGRectMake(15+emailImg.size.width+9, 19, 60, 16)];
        [bg1 addSubview:emailNote];
        [emailNote setFont:[UIFont fontWithName:kFontNameLightHeiti size:16]];
        emailNote.textColor = [UIColor colorWithHex:0xff979797];

        emailNote.text = @"用户名";
        [emailNote release];
        
        
        _userNameLabel = [[UITextField alloc] initWithFrame:CGRectMake(110, 35, 190, 20)];
        [self addSubview:_userNameLabel];
        [_userNameLabel setBackgroundColor:[UIColor clearColor]];
        _userNameLabel.clearButtonMode = UITextFieldViewModeWhileEditing;
        _userNameLabel.font = [UIFont systemFontOfSize:16];
        _userNameLabel.tag = kTagUserName;
        _userNameLabel.returnKeyType = UIReturnKeyDone;
        _userNameLabel.delegate = self;
        [_userNameLabel release];
        
        _userNameWrongLabel = [[UILabel alloc]initWithFrame:CGRectMake(230, 39, 70, 12)];
        _userNameWrongLabel.backgroundColor = [UIColor clearColor];
        _userNameWrongLabel.textColor = [UIColor redColor];
        _userNameWrongLabel.textAlignment = UITextAlignmentRight;
        _userNameWrongLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:12];
        [self addSubview:_userNameWrongLabel];
        _userNameWrongLabel.hidden = YES;
        [_userNameWrongLabel release];
        
        UIImageView *bg2 = [[[UIImageView alloc] initWithFrame:CGRectMake(14, 17+47, 320-14*2, 47)] autorelease];
        UIImage *img2 = [UIImage imageNamed:@"form_bg2"];
        bg2.image = img2;
        [self addSubview:bg2];
        
        UIImage *passwordImg = [UIImage imageNamed:@"icon_password"];
        UIImageView *password = [[UIImageView alloc] initWithFrame:CGRectMake(15, 20, passwordImg.size.width, passwordImg.size.height)];
        password.image = passwordImg;
        [bg2 addSubview:password];
        [password release];
        
        
        UILabel *passwordNote = [[UILabel alloc] initWithFrame:CGRectMake(15+passwordImg.size.width+9, 19, 40, 16)];
        [bg2 addSubview:passwordNote];
        [passwordNote setFont:[UIFont fontWithName:kFontNameLightHeiti size:16]];
        passwordNote.textColor = [UIColor colorWithHex:0xff979797];
        passwordNote.text = @"密码";
        [passwordNote release];
        
       
        
        _userPassword = [[UITextField alloc] initWithFrame:CGRectMake(110, 35+47, 190, 20)];
        _userPassword.secureTextEntry = YES;
        _userPassword.font = [UIFont systemFontOfSize:16];
        _userPassword.delegate = self;
        _userPassword.returnKeyType = UIReturnKeyDone;
        _userPassword.tag = kTagPassWord;

        _userPassword.clearButtonMode = UITextFieldViewModeWhileEditing;

        [self addSubview:_userPassword];
        [_userPassword release];
        
        _loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(14, 130, 320-28, 40)];
        [_loginBtn setTitle:@"登陆" forState:UIControlStateNormal];
        [self addSubview:_loginBtn];
        UIImage *loginIMG = [UIImage imageNamed:@"login_btn"];
        [_loginBtn setBackgroundImage:loginIMG forState:UIControlStateNormal];
//        [loginBtn setBackgroundColor:[UIColor blackColor]];
        [_loginBtn addTarget:self action:@selector(loginPress:) forControlEvents:UIControlEventTouchUpInside];
        [_loginBtn release];
        
        
        
        _regBtn = [[UIButton alloc] initWithFrame:CGRectMake(14, 190, 320-28, 40)];
        [_regBtn setTitle:@"注册" forState:UIControlStateNormal];
        [self addSubview:_regBtn];
        [_regBtn setBackgroundImage:loginIMG forState:UIControlStateNormal];
        [_regBtn addTarget:self action:@selector(regBtnPress:) forControlEvents:UIControlEventTouchUpInside];
        [_regBtn release];
        
        [self setBackgroundColor:[UIColor colorWithHex:0xfff4f4f4]];
        
        _indicatorView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 32, 32)];
        _indicatorView.center = self.center;
        [_indicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
        [_indicatorView setBackgroundColor:[UIColor clearColor]];
        [self addSubview:_indicatorView];
        [_indicatorView release];

    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (void) bgClick
{
    [_userNameLabel resignFirstResponder];
    [_userPassword resignFirstResponder];
}

- (void) loginPress:(id) sender
{
    
//    if ([_delegate respondsToSelector:@selector(startLoginWithUserName:andPassword:)]) {
//        [_delegate startLoginWithUserName:_userNameLabel.text andPassword:_userPassword.text];
//    }
    
    NSString *userName = _userNameLabel.text;
    NSString *pass = _userPassword.text;
    if (userName == nil || [NSString stringIsNullOrEmpty:pass] ) {
        [RCAppDelegate alertWithCustomizeString:@"请完整填写信息"];
        return;
    }
    
    NSString *final = [_userNameLabel.text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
    if ([final isEqualToString:@""]) {
        _userNameWrongLabel.text = @"用户名错误";
        _userNameWrongLabel.hidden = NO;
        _loginBtn.enabled = NO;
        return;
    }
//    NSError * error = NULL;
//    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})$" options:0 error:&error];
//    NSTextCheckingResult * result = [regex firstMatchInString:userName options:0 range:NSMakeRange(0, [userName length])];
//    if (!result || (regex.numberOfCaptureGroups + 1) != result.numberOfRanges) {
//       
//    }
    
    [[GloableEngineService sharedInstance]saveUserEmailName:_userNameLabel.text];

    int64_t reqID = [[IManager sharedInstance] requestLogin:_userNameLabel.text withPassword:_userPassword.text withDelegate:self];
    
    if (reqID != kInvalidRequestId)         [_indicatorView startAnimating];


}

- (void) regBtnPress:(id) sender
{
    if ([_delegate respondsToSelector:@selector(regBtnClick)]) {
        [_delegate regBtnClick];
    }
}

- (void) updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId
{
    [_indicatorView stopAnimating];
      RCLoginDataModel  *data = (RCLoginDataModel *)dataModel;
    if (data.errorNO == 0) {
        
        [[GloableEngineService sharedInstance] saveUserLoginInfo:data];
        
        [_delegate loginSuccess];
    }else{
        [_delegate loginFail];
    }
    
}

- (void) updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId
{
    [_indicatorView stopAnimating];
    [RCAppDelegate alertWithCustomizeString:@"登录失败"];
}

#pragma UITextFieldDelegate


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag == kTagUserName) {
//        NSString *userName = textField.text;
        
        NSString *final = [textField.text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
        if ([final isEqualToString:@""]) {
            _userNameWrongLabel.text = @"用户名错误";
            _userNameWrongLabel.hidden = NO;
            _loginBtn.enabled = NO;
            return;
        }
        
//        NSError * error = NULL;
//        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})$" options:0 error:&error];
//        NSTextCheckingResult * result = [regex firstMatchInString:userName options:0 range:NSMakeRange(0, [userName length])];
//        if (!result || (regex.numberOfCaptureGroups + 1) != result.numberOfRanges) {
//            _userNameWrongLabel.text = @"用户名错误";
//            _userNameWrongLabel.hidden = NO;
//            _loginBtn.enabled = NO;
//            return;
//        }
    }
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    if (textField.tag == kTagUserName) {
        _userNameWrongLabel.hidden = YES;
        _loginBtn.enabled = YES;
    }
}

@end
